/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.bastian.hinterleitner;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import de.bastian.hinterleitner.adaptersviews.CategorySelectAdapter;
import de.bastian.hinterleitner.adaptersviews.CurrencyAdapter;
import de.bastian.hinterleitner.database.DataHelper;
import de.bastian.hinterleitner.tools.Category;
import de.bastian.hinterleitner.tools.Constants;
import de.bastian.hinterleitner.tools.Entry;
import de.bastian.hinterleitner.tools.Unit;
import de.bastian.hinterleitner.tools.UpdateWidgetService;
import de.hijacksoft.wyc.R;

/**
 * 
 * @author basti
 */
public class NewEntry extends Activity implements OnClickListener {

	private EditText value;
	private AutoCompleteTextView name;
	private Spinner category, currency;
	private Button ok, cancel, button_value, date, dateEnd;
	private ImageButton repeat, delete;
	private TextView header;
	private ArrayAdapter<Entry> adapter;

	private Date end = new Date(Calendar.getInstance().get(Calendar.YEAR),
			Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance()
					.get(Calendar.DAY_OF_MONTH));

	private boolean repeatable = false;
	private int repeatID = -1;

	private ArrayList<Category> categories;

	private final int DATE_PICKER = 0;
	private final int DATE_PICKER_END = 1;
	
	private int xthdate = 1;

	private int editedItemId = -1;
	private Entry editedItem = new Entry("undefined");

	private static final String TAG = "WatchYourCash_NewEntry";

	private final int STATUS_SINGLE = 0;
	private final int STATUS_ALL = 2;

	private int status = STATUS_SINGLE;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.activity_newentry);

		Intent i = getIntent();

		if (i.getExtras() != null) {
			editedItemId = Integer.parseInt(i.getStringExtra("itemId"));
		}

		initGui();

		if (initEditing()) {
			if (editedItem.getRepeatableReference() != -1) {
				showRepeatableQuestion();
			} else {
				initEditedItemGUI();
			}
		}
	}

	private void showRepeatableQuestion() {
		String[] options = { getString(R.string.onlythis),
				getString(R.string.allfuture), getString(R.string.allofthis) };
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.repeatable));
		builder.setSingleChoiceItems(options, 0,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int buttonId) {
						status = buttonId;
					}
				});
		builder.setPositiveButton(getString(R.string.ok),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int buttonId) {
						if (status == STATUS_ALL) {
							editedItem = DataHelper
									.getDataHelper(NewEntry.this)
									.getAllRepeatables(
											editedItem.getRepeatableReference())
									.get(0);
							if (editedItem == null)
								finish();
							else
								editedItemId = editedItem.getId();
						}
						repeatable = status > 0;
						initEditedItemGUI();
					}
				});
		builder.setNegativeButton(getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int buttonId) {
						finish();
					}
				});
		Dialog d = builder.create();
		d.show();
	}

	private boolean initEditing() {
		if (editedItemId != -1) {
			DataHelper helper = DataHelper.getDataHelper(this);
			Entry e = helper.getEntryById(editedItemId);
			editedItem = e;
		}

		return editedItemId != -1;
	}

	private void initEditedItemGUI() {
		header.setText(editedItem.getName());
		date.setText(editedItem.getDay() + "." + editedItem.getMonth() + "."
				+ editedItem.getYear());
		name.setText(editedItem.getName());
		value.setText("" + Math.abs(editedItem.getValue()));
		if (editedItem.getValue() > 0) {
			button_value.setText("+");
		}
		if (editedItem.getRepeatableReference() != -1) {
			end = DataHelper.getDataHelper(this)
					.getLatestRepeatable(editedItem.getRepeatableReference())
					.getDate();
			// 1900 bug
			end.setYear(end.getYear()+1900);
		} else {
			end = editedItem.getDate();
		}
		updateSpinner();
		updateCategorySpinner();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Constants.RESULT_KILLME)
			finish();
	}

	private void initGui() {
		name = (AutoCompleteTextView) findViewById(R.id.newentry_edittext_name);
		value = (EditText) findViewById(R.id.newentry_edittext_value);
		category = (Spinner) findViewById(R.id.newentry_spinner_category);
		currency = (Spinner) findViewById(R.id.newentry_spinner_currency);
		button_value = (Button) findViewById(R.id.newentry_button_value);
		ok = (Button) findViewById(R.id.newentry_button_ok);
		cancel = (Button) findViewById(R.id.newentry_button_cancel);
		date = (Button) findViewById(R.id.newentry_button_date);
		repeat = (ImageButton) findViewById(R.id.newentry_button_repeat);
		header = (TextView) findViewById(R.id.newentry_text_new);
		delete = (ImageButton) findViewById(R.id.newentry_button_delete);

		adapter = new ArrayAdapter<Entry>(this,
				android.R.layout.simple_dropdown_item_1line, DataHelper
						.getDataHelper(this).getAllEntriesGroupedByName());
		
		name.setOnItemClickListener(new OnItemClickListener() {

	        @Override
	        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
	                long arg3) {
	        	try{
    	            Entry item = (Entry) arg0.getItemAtPosition(arg2);
    	            category.setSelection(categories.indexOf(item
    						.getCategory()));
    				DataHelper dh = DataHelper.getDataHelper(NewEntry.this);
    				checkValue(dh.getAllEntriesContaining(name.getText()
    						.toString()));
	        	}catch(Exception e){
	        		value.setHint(getString(R.string.value));
	        	}
				checkButton();
	        }

	    });
		
		name.setAdapter(adapter);

		button_value.setOnClickListener(this);
		ok.setOnClickListener(this);
		cancel.setOnClickListener(this);
		date.setOnClickListener(this);
		repeat.setOnClickListener(this);
		delete.setOnClickListener(this);

		if (editedItemId != -1) {
			delete.setVisibility(View.VISIBLE);
		}

		int year = Calendar.getInstance().get(Calendar.YEAR);
		int month = Calendar.getInstance().get(Calendar.MONTH);
		int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

		editedItem.setDate(year, month + 1, day);
		date.setText(day + "." + (month + 1) + "." + year);

		initSpinner();
		initCurrencySpinner();

		SharedPreferences sp = getSharedPreferences("values", MODE_PRIVATE);
		String unit = sp.getString("unit", getString(R.string.currency));
		currency.setSelection(Constants.getUnits(this).indexOf(unit));

		name.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				checkButton();
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}

		});

		value.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
				checkButton();
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}

		});

		checkButton();

		header.requestFocus();
	}

	private void checkValue(ArrayList<Entry> entries) {
		double val = 0;
		int maxCount = 0;
		for (int i = 0; i < entries.size(); i++) {
			int count = count(entries.get(i).getName(), entries);
			if (count > maxCount) {
				String entryName = entries.get(i).getName();
				val = probableValueOf(entryName,
						entriesWithName(entryName, entries));
			}
		}
		if (val > 0) {
			button_value.setText("+");
		} else {
			button_value.setText("-");
		}
		value.setHint(Math.abs(roundToDecimals(2, val)) + "");
	}

	private ArrayList<Entry> entriesWithName(String name,
			ArrayList<Entry> entries) {
		ArrayList<Entry> result = new ArrayList<Entry>();
		for (int i = 0; i < entries.size(); i++) {
			if (entries.get(i).getName().equals(name)) {
				result.add(entries.get(i));
			}
		}
		return result;
	}
	
	private double probableValueOf(String name, ArrayList<Entry> entries){
		HashMap<Double, Integer> counts = new HashMap<Double, Integer>();
		for(int i=0; i<entries.size(); i++){
			Entry e = entries.get(i);
			if(counts.containsKey(e.getValue())){
				counts.put(e.getValue(), counts.get(e.getValue())+1);
			}else{
				counts.put(e.getValue(), 1);
			}
		}
		int occurences = 0;
		double val = 0;
		Set<Double> keys = counts.keySet();
		for(Double k : keys){
			int count = counts.get(k);
			if(count>occurences){
				occurences = count;
				val = k;
			}
		}		
		return val;
	}

	private int count(String name, ArrayList<Entry> entries) {
		int count = 0;
		for (int i = 0; i < entries.size(); i++) {
			if (entries.get(i).getName().equals(name)) {
				count++;
			}
		}
		return count;
	}

	public final double roundToDecimals(int decimals, double src) {
		return (int) (src * Math.pow(10, decimals)) / Math.pow(10, decimals);
	}

	private void checkButton() {
		String name = this.name.getText().toString();

		for (int i = 0; i < name.length(); i++) {
			if (name.startsWith(" ")) {
				name.replaceFirst(" ", "");
			}
		}

		if (name.length() == 0) {
			ok.setEnabled(false);
			return;
		}
		try {
			Double.parseDouble(button_value.getText().toString()
					+ this.value.getText().toString());
		} catch (NumberFormatException ex) {
			try {
				Double.parseDouble(button_value.getText().toString()
						+ this.value.getHint().toString());
			} catch (NumberFormatException e) {
				ok.setEnabled(false);
				return;
			}
		}
		ok.setEnabled(true);
	}

	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.newentry_button_value:
			if (button_value.getText().equals("-")) {
				button_value.setText("+");
			} else {
				button_value.setText("-");
			}
			break;
		case R.id.newentry_button_ok:
			insertEntry();
			break;
		case R.id.newentry_button_cancel:
			finish();
			break;
		case R.id.newentry_button_date:
			showDialog(DATE_PICKER);
			break;
		case R.id.newentry_button_repeat:
			showRepeatDialog();
			break;
		case R.id.newentry_button_delete:
			showDeleteDialog();
			break;
		}
	}

	private void showDeleteDialog() {
		DialogInterface.OnClickListener positive = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (repeatable && editedItem.getRepeatableReference() != -1) {
					Command c = new Command() {
						@Override
						public void execute() {
							DataHelper.getDataHelper(NewEntry.this)
									.deleteAllRepeatablesSince(editedItem);
						}
					};
					new Update(c).execute();
				} else {
					DataHelper.getDataHelper(NewEntry.this).delete(editedItem);
					setResult(RESULT_OK);
					finish();
				}
			}
		};
		question(
				getString(R.string.deletequestion).replace("$1",
						editedItem.getName()), getString(R.string.yes),
				getString(R.string.no), positive, null);
	}

	private void showRepeatDialog() {
		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle(getString(R.string.repeatable));

		LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = inflator.inflate(R.layout.dialog_repeat, null);
		alertDialog.setView(view);

		dateEnd = (Button) view.findViewById(R.id.repeat_button_date);
		if (end.getTime() <= editedItem.getDate().getTime()) {
			end = new Date(editedItem.getDate().getTime());
		}
		dateEnd.setText(end.getDate() + "." + (end.getMonth() + 1) + "."
				+ end.getYear());
		final RadioGroup rg = (RadioGroup) view
				.findViewById(R.id.repeat_radiogroup);
		
		/*rg.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
					final AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext()).create();
					alertDialog.setTitle(getString(R.string.repeatable));
					final EditText xth = new EditText(getApplicationContext());
					xth.setText(xthdate+"");
					alertDialog.setView(xth);
					alertDialog.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							xthdate = Integer.parseInt(xth.getText().toString());
						}
					});
					alertDialog.setButton2(getString(R.string.cancel),new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// nothing
						}
					});
					alertDialog.show();
					updateRadioGroup(rg);
			}
		});*/
		
		for(int i=0; i<rg.getChildCount(); i++){
			rg.getChildAt(i).setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					String amountString = "???";
					switch (v.getId()) {
        				case R.id.repeat_radio_daily:
        					amountString = getString(R.string.everyxthday);
        					break;
        				case R.id.repeat_radio_weekly:
        					amountString = getString(R.string.everyxthweek);
        					break;
        				case R.id.repeat_radio_monthly:
        					amountString = getString(R.string.everyxthmonth);
        					break;
        				case R.id.repeat_radio_yearly:
        					amountString = getString(R.string.everyxthyear);
        					break;
    				}
					final AlertDialog amountDialog = new AlertDialog.Builder(alertDialog.getContext()).create();
					amountDialog.setTitle(amountString.replace("$1","???"));
					final EditText xth = new EditText(getApplicationContext());
					xth.setText(xthdate+"");
					xth.setInputType(InputType.TYPE_CLASS_NUMBER);
					amountDialog.setView(xth);
					amountDialog.setButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							xthdate = Integer.parseInt(xth.getText().toString());
							updateRadioGroup(rg);
							amountDialog.dismiss();
						}
					});
					amountDialog.setButton2(getString(R.string.cancel),new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							amountDialog.dismiss();
						}
					});
					amountDialog.setOnDismissListener(new OnDismissListener() {						
						@Override
						public void onDismiss(DialogInterface dialog) {
							closeKeyboard(xth);
						}
					});
					amountDialog.show();
				}
			});
		}
		
		rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				int years = 0;
				int months = 0;
				int days = 0;
				repeatID = checkedId;
				switch (checkedId) {
    				case R.id.repeat_radio_daily:
    					days = 1;
    					break;
    				case R.id.repeat_radio_weekly:
    					days = 7;
    					break;
    				case R.id.repeat_radio_monthly:
    					months = 1;
    					break;
    				case R.id.repeat_radio_yearly:
    					years = 1;
    					break;
				}
				int year = editedItem.getYear();
				int month = editedItem.getMonth() - 1;
				int day = editedItem.getDay();
				Date hypotheticalDate = new Date(year + years, month + months,
						day + days);
				if (hypotheticalDate.getTime() > end.getTime()) {
					end = hypotheticalDate;
					updateEndButton();
				}
				
				updateRadioGroup(rg);
			}
		});

		dateEnd.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(DATE_PICKER_END);
			}
		});

		alertDialog.setButton(getString(R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						repeatID = rg.getCheckedRadioButtonId();
						repeatable = true;
					}
				});

		alertDialog.setButton2(getString(R.string.cancel),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// nothing
					}
				});

		alertDialog.show();
		
		if(repeatID>0){
			rg.check(repeatID);
			updateRadioGroup(rg);
		}
	}
	
	private void updateRadioGroup(RadioGroup rg){
		int checked = rg.getCheckedRadioButtonId();
		for(int i=0; i<rg.getChildCount(); i++){
			RadioButton button = (RadioButton)rg.getChildAt(i);
			button.setText(getTextForRadioButton(button.getId(), button.getId()==checked));
		}
	}
	

	private CharSequence getTextForRadioButton(int id, boolean checked) {
		if(xthdate==1)checked=false;
		if(checked){
			switch(id){
    		case R.id.repeat_radio_daily:
    			return getString(R.string.everyxthday).replace("$1",xthdate+"");
    		case R.id.repeat_radio_weekly:
    			return getString(R.string.everyxthweek).replace("$1",xthdate+"");
    		case R.id.repeat_radio_monthly:
    			return getString(R.string.everyxthmonth).replace("$1",xthdate+"");
    		case R.id.repeat_radio_yearly:
    			return getString(R.string.everyxthyear).replace("$1",xthdate+"");
    		}
    		return "???";
		}else{
    		switch(id){
    		case R.id.repeat_radio_daily:
    			return getString(R.string.everyday);
    		case R.id.repeat_radio_weekly:
    			return getString(R.string.everyweek);
    		case R.id.repeat_radio_monthly:
    			return getString(R.string.everymonth);
    		case R.id.repeat_radio_yearly:
    			return getString(R.string.everyyear);
    		}
    		return "???";
		}
	}

	private boolean insertEntry() {

		double value;

		try {
			value = Double.parseDouble(button_value.getText().toString()
					+ this.value.getText().toString());
		} catch (Exception e) {
			try {
				value = Double.parseDouble(button_value.getText().toString()
						+ this.value.getHint().toString());
			} catch (Exception ex) {
				ok.setEnabled(false);
				return false;
			}
		}

		String name = this.name.getText().toString();

		while (name.startsWith(" ")) {
			name.replaceFirst(" ", "");
		}

		if (name.equals("")) {
			return false;
		}

		int year = editedItem.getYear();
		int month = editedItem.getMonth();
		int day = editedItem.getDay();

		int repeatableReference = -1;
		if (repeatable) {
			repeatableReference = editedItem.getRepeatableReference();
		}

		String unit = currency.getSelectedItem().toString();

		editedItem = new Entry(name, value, editedItemId);
		try {
			editedItem.setCategory((Category) category.getSelectedItem());
		} catch (ClassCastException e) {
			editedItem.getCategory().name = category.getSelectedItem()
					.toString();
		}
		editedItem.setDate(year, month, day);
		editedItem.setRepeatableReference(repeatableReference);
		editedItem.setUnit(Unit.get(unit, this));

		final DataHelper h = DataHelper.getDataHelper(this);

		final boolean eachyear = repeatID == R.id.repeat_radio_yearly;
		final boolean eachmonth = repeatID == R.id.repeat_radio_monthly;
		final int eachday = (repeatID == R.id.repeat_radio_daily) ? 1
				: (repeatID == R.id.repeat_radio_weekly) ? 7 : 0;

		if (editedItemId == -1) {

			SharedPreferences sp = getSharedPreferences("values", MODE_PRIVATE);
			sp.edit().putString("unit", unit).commit();

			if (repeatable && repeatID != -1) {
				Command c = new Command() {
					@Override
					public void execute() {
						h.addRepeatable(editedItem, eachyear ? xthdate : 0,
								eachmonth ? xthdate : 0, xthdate*eachday, end.getTime());
					}
				};
				new Update(c).execute();
			} else {
				h.insert(editedItem);
				close();
			}
		} else {
			if (repeatable) {
				Command c = new Command() {
					@Override
					public void execute() {
						if (editedItem.getRepeatableReference() == -1) {
							h.addRepeatable(editedItem, eachyear ? xthdate : 0,
									eachmonth ? xthdate : 0, xthdate*eachday, end.getTime());
						} else {
							h.updateRepeatable(editedItem, eachyear ? xthdate : 0,
									eachmonth ? xthdate : 0, xthdate*eachday, end.getTime());
						}
					}
				};
				new Update(c).execute();
			} else {
				editedItem.setRepeatableReference(-1);
				h.update(editedItem);
				close();
			}
		}

		return true;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_PICKER:
			DatePickerDialog pd = new DatePickerDialog(this, mDateSetListener,
					editedItem.getYear(), editedItem.getMonth() - 1,
					editedItem.getDay());
			return pd;
		case DATE_PICKER_END:
			DatePickerDialog pd2 = new DatePickerDialog(this,
					mDateEndSetListener, end.getYear(), end.getMonth(),
					end.getDate());
			return pd2;
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int month, int day) {
			editedItem.setDate(year, month + 1, day);
			date.setText(day + "." + (month + 1) + "." + year);
		}
	};

	private DatePickerDialog.OnDateSetListener mDateEndSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int month, int day) {
			end = new Date(year, month, day);
			updateEndButton();
		}
	};

	private void updateEndButton() {
		dateEnd.setText(end.getDate() + "." + (end.getMonth() + 1) + "."
				+ end.getYear());
	}

	private void initSpinner() {
		DataHelper d = DataHelper.getDataHelper(this);
		categories = d.getAllCategories();
		categories.add(new Category("... " + getString(R.string.newcategory),
				null, -1));
		CategorySelectAdapter adapter = new CategorySelectAdapter(this,
				categories);
		category.setAdapter(adapter);
		updateSpinner();
		category.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (arg2 == categories.size() - 1) {
					int pos = categories
							.indexOf(getString(R.string.uncategorized));
					if (pos >= 0)
						category.setSelection(pos);
					else
						category.setSelection(0);
					addCategory();
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}

		});
	}

	private void updateSpinner() {
		int pos = categories.indexOf(editedItem.getCategory());
		if (pos >= 0)
			category.setSelection(pos);
	}

	private void initCurrencySpinner() {
		List<String> units = Constants.getUnits(this);

		CurrencyAdapter adapter = new CurrencyAdapter(this, units);

		currency.setAdapter(adapter);

		updateCategorySpinner();

	}

	private void updateCategorySpinner() {
		List<String> units = Constants.getUnits(this);
		Unit unit = editedItem.getUnit();
		if (unit == null) {
			unit = Unit.get(getString(R.string.currency), this);
		}
		int pos = units.indexOf(unit.getSign());
		if (pos >= 0) {
			currency.setSelection(pos);
		}
	}

	private void addCategory() {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setTitle(getString(R.string.newcategory));

		final EditText name = new EditText(this);
		name.setHint(getString(R.string.name));
		name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);

		final TextView cat = new TextView(this);
		cat.setText(R.string.icon);
		cat.setTextColor(Color.WHITE);

		CategorySelectAdapter adapter = new CategorySelectAdapter(this,
				toCategories(Constants.iconNames()));
		final Spinner spinner = new Spinner(this);
		spinner.setAdapter(adapter);
		spinner.setPrompt(getString(R.string.iconselectsimple));

		LinearLayout view = new LinearLayout(this);
		view.setOrientation(LinearLayout.VERTICAL);
		view.addView(name);
		view.addView(cat);
		view.addView(spinner);

		alertDialog.setView(view);

		alertDialog.setButton(getString(R.string.ok),
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						DataHelper dh = DataHelper.getDataHelper(NewEntry.this);
						String icon = Constants.iconNames().get(
								spinner.getSelectedItemPosition());
						Category cat = new Category(name.getText().toString(),
								icon, -1);
						if (!dh.addCategory(cat)) {
							dialog(getString(R.string.alreadyexists));
						} else {
							editedItem.getCategory().name = name.getText()
									.toString();
							initSpinner();
						}
					}
				});

		alertDialog.setButton2(getString(R.string.cancel),
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});

		alertDialog.show();
	}

	private ArrayList<Category> toCategories(ArrayList<String> iconNames) {
		ArrayList<Category> result = new ArrayList<Category>();
		for (int i = 0; i < iconNames.size(); i++) {
			result.add(new Category(iconNames.get(i), iconNames.get(i), -1));
		}
		return result;
	}

	public final void dialog(String text) {
		final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setMessage(text);
		alertDialog.setCanceledOnTouchOutside(true);
		alertDialog.setButton(getString(R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						alertDialog.cancel();
					}
				});
		alertDialog.show();
	}

	public final void question(String text, String yesText, String noText,
			DialogInterface.OnClickListener positive,
			DialogInterface.OnClickListener negative) {
		AlertDialog alertDialog = new AlertDialog.Builder(this).create();
		alertDialog.setMessage(text);
		alertDialog.setButton(yesText, positive);
		alertDialog.setButton2(noText, negative);
		alertDialog.show();
	}

	private interface Command {
		public void execute();
	}

	private class Update extends AsyncTask {

		ProgressDialog pd = new ProgressDialog(NewEntry.this);
		Command c;

		public Update(Command c) {
			this.c = c;
			if (c == null) {
				this.c = new Command() {
					@Override
					public void execute() {
					}
				};
			}
		}

		@Override
		protected void onPreExecute() {
			pd.setMessage(getString(R.string.updateingdatabase));
			pd.show();
		}

		@Override
		protected Object doInBackground(Object... arg0) {
			c.execute();
			return null;
		}

		@Override
		protected void onPostExecute(Object result) {
			pd.dismiss();
			close();
		}

	}

	private void close() {
		// update widget
		Intent widgetUpdateIntent = new Intent(this, UpdateWidgetService.class);
		startService(widgetUpdateIntent);
		setResult(RESULT_OK);
		finish();
	}
	
	private void closeKeyboard(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	}

}